package com.pda.smallbug.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.pda.smallbug.myapplication.httpDomain.MainHttp;
import com.pda.smallbug.myapplication.httpDomain.NextHttp;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

public class MainActivity extends Activity {

    private RecyclerView recyclerView;
    private MainAdapter adapter;
    private List<MainHttp.MainData> data=new ArrayList<>();
    /**
     *自动轮播时间间隔默认3秒
     */
    private long mCycleDelayed=10000;
    private boolean shouldPlayBeep=true;
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        setAudio();
        EventBus.getDefault().register(this);
        recyclerView=(RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,false));
        adapter=new MainAdapter(MainActivity.this);
        recyclerView.setAdapter(adapter);
        getData();

    }
    private Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            getData();
            return false;
        }
    });
    public void onEventMainThread(MyEvent event)
    {
        if (event.getCode()==1){
            getData();
        }
    }

    public boolean equalList(List<String> list1, List<String> list2) {
        if (list1.size() != list2.size())
            return false;
        if (list1.containsAll(list2))
            return true;
        return false;
    }
    private void getData(){
        RequestParams requestParams=new RequestParams(MyApplication.url+"tools/submit_ajax.ashx?action=getpclist");
        requestParams.addBodyParameter("fuserid",MyApplication.mySharedPreferences.getString("id",""));
        x.http().post(requestParams, new Callback.CacheCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson=new Gson();
                MainHttp http= gson.fromJson(result,MainHttp.class);
                if (http.getStatus()==1){
                    List<MainHttp.MainData> newdata = http.getData();
                    ArrayList<String> a=new ArrayList();
                    for (MainHttp.MainData i:newdata) {
                        a.add(i.getFBillNo());
                    }
                    ArrayList<String> b=new ArrayList();
                    for (MainHttp.MainData i:data) {
                        b.add(i.getFBillNo());
                    }
                    boolean haha=equalList(a,b);
                    if (!haha){
                        if (shouldPlayBeep && mediaPlayer != null) {
                            mediaPlayer.start();
                        }
                    }
                    data.clear();
                    data.addAll(newdata);
                    adapter.update(data);
                    handler.sendEmptyMessageDelayed(0,mCycleDelayed);
                }else {
                    Toast.makeText(MainActivity.this,http.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("asd",ex.toString());
                Toast.makeText(MainActivity.this,"网络请求失败",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public boolean onCache(String result) {
                return false;
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mediaPlayer!=null){
            if (mediaPlayer.isPlaying()){
                mediaPlayer.stop();
            }
        }
    }

    private void setAudio(){
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int ringerMode = am.getRingerMode();
        //ringerMode为手机的系统声音设置的状态值，0位静音，1为震动，2为响铃，下面就是通知的设置
        if (ringerMode != AudioManager.RINGER_MODE_NORMAL) {
            shouldPlayBeep = false;
        }
        if (shouldPlayBeep){
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            // 注册事件。当播放完毕一次后，重新指向流文件的开头，以准备下次播放。
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer player) {
                    player.seekTo(0);
                }
            });
            //  设定数据源，并准备播放
            AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
                file.close();
                // mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException ioe) {
                mediaPlayer = null;
            }
        }
    }
}
